<?php
class PaypalINPlisternerController extends ControllerBase {
	public function indexAction() {
		
		//error_reporting(E_ALL ^ E_NOTICE); 		$email = "thien1988@gmail.com"; //$_GET['ipn_email']; 		$header = "";
		$emailtext = "";
		
		// Read the post from PayPal and add 'cmd' 		$req = 'cmd=_notify-validate';
		$get_magic_quotes_exits = false;
		if (function_exists ( 'get_magic_quotes_gpc' )) {
			$get_magic_quotes_exits = true;
		}
		
		// Handle escape characters, which depends on setting of magic quotes 		foreach ( $_POST as $key => $value ) {
			if ($get_magic_quotes_exits == true && get_magic_quotes_gpc () == 1) {
				$value = urlencode ( stripslashes ( $value ) );
			} else {
				$value = urlencode ( $value );
			}
			$req .= "&$key=$value";
		}
		
		// Post back to PayPal to validate 		$header .= "POST /cgi-bin/webscr HTTP/1.0\r\n";
		$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
		$header .= "Content-Length: " . strlen ( $req ) . "\r\n\r\n";
		//$fp = fsockopen ('ssl://www.paypal.com', 443, $errno, $errstr, 30); 
		$fp = fsockopen ( 'www.sandbox.paypal.com', 80, $errno, $errstr, 30 );
		
		if (! $fp) { // HTTP ERROR 		} else {
			// NO HTTP ERROR 			fputs ( $fp, $header . $req );
			while ( ! feof ( $fp ) ) {
			
			}
			$res = fgets ( $fp, 1024 );
			if (strcmp ( $res, "VERIFIED" ) == 0) {
				
				foreach ( $_POST as $key => $value ) {
					$emailtext .= $key . " = " . $value . "\n\n";
				}
				mail ( $email, "Live-VERIFIED IPN", $emailtext . "\n\n" . $req );
			} else if (strcmp ( $res, "INVALID" ) == 0) {
				// If 'INVALID', send an email. TODO: Log for manual investigation. 				foreach ( $_POST as $key => $value ) {
					$emailtext .= $key . " = " . $value . "\n\n";
				}
				mail ( $email, "Live-INVALID IPN", $emailtext . "\n\n" . $req );
			}
		}
		fclose ( $fp );
	
	}
}